#coding=utf-8
import datetime,cgi,urllib
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

modify_url = 'https://www.dnspod.com/API/Record.Modify'
jayproxy_domain_id = '340422'
www_record_id = '1376388'

jayproxy_url = 'http://www.jayproxy.com/t.txt'

vps = {
    #hp':['A', '218.75.54.186'],
    'fdd':['A', '69.197.153.239'],
    'zjuer':['A', '64.71.167.13'],
    #'rp':['CNAME', 'ghs.jayproxy.com'],
    'bt':['A', '173.212.207.16'],    
    }

class Record(db.Model):
    name = db.StringProperty()
    addr = db.StringProperty()
    date = db.DateTimeProperty()

def now():
    return datetime.datetime.now() + datetime.timedelta(hours=+8)
           
def check_connect(url):
    try:
        result = urlfetch.fetch(url, method=urlfetch.GET, deadline=5)  
    except urlfetch.Error, e:
        return False
    else:
        if result.status_code == 200:
            return True
        else:
            return False

def modify_dns(record_type, value):

    data = {'login_email':'xiaojay@gmail.com',
            'login_password':'101783',
            'format':'json',
            'domain_id':jayproxy_domain_id,
            'record_id':www_record_id,
            'sub_domain':'www',
            'record_type':record_type,
            'record_line':'default',
            'value':value,
            'mx':'1',
            'ttl':'600'}
            
    result = urlfetch.fetch(modify_url, payload=urllib.urlencode(data), method=urlfetch.POST, deadline=10)
    return result.status_code, result.content    
    
class URLChecker(webapp.RequestHandler):
  def get(self):
    url = self.request.get('url')
    if check_connect(url):
        self.response.out.write('%s:could be retched.'%url)
    else:
        self.response.out.write('%s:seems down.'%url)

class DNSModifier(webapp.RequestHandler):
  def get(self):
    r = modify_dns('A', '218.75.54.186')
    self.response.out.write('%s:%s'%(r[0], r[1]))
    
class Rabbit(webapp.RequestHandler):
    def get(self):
        q = Record.all()
        q.order('-date')
        n = q.count()
        
        if n != 0:
            m5 = datetime.timedelta(minutes=5)
            r = q.fetch(1)[0]
            last_modified_at = r.date
            
            self.response.out.write( 'Jayproxy is mapped to %s.(%s)<br/>'%(r.name, r.date) )
            
            if (now() - last_modified_at) < m5:
                return
            
        if check_connect(jayproxy_url):
            self.response.out.write('Jayproxy is ok :-)<br/>')
            return
        
        self.response.out.write('Jayproxy is down :-(<br/>')
        for n in ['bt', 'zjuer', 'fdd']:
            v = vps[n]
            url = 'http://' + v[1] + '/t.txt'
            if check_connect(url):
                r = modify_dns(v[0], v[1])
                if r[0] == 200:
                    self.response.out.write('Jayproxy is mapped to %s right now.<br/>'%n)
                    Record(name=n, addr=v[1], date=now()).put()
                    return 
                            
application = webapp.WSGIApplication([
  ('/check_url', URLChecker),
  ('/modify_dns', DNSModifier),
  ('/rabbit3', Rabbit),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
  
